package com.aaa.stream.demo04;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.awt.event.ItemEvent;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author C-Q
 * @version 1.1.0
 * @Description: collect--搜集操作
 * @date 2022/11/5
 */
public class CollectTest {
    public static void main(String[] args) {
            //假设有个Person类和一个Person列表，现在有两个需求:
            //1.找到年龄大于18岁的人并输出；
            //2.找出所有中国人的数量
            ArrayList<Person> people = new ArrayList<>();
            people.add(new Person("上官雪", 18, "中国", 'A'));
            people.add(new Person("慕容复", 14, "法国", 'B'));
            people.add(new Person("逍遥散", 57, "伊拉克", 'B'));
            people.add(new Person("宇文都", 36, "比利时", 'B'));
            people.add(new Person("易烊玺", 45, "中国", 'A'));
            people.add(new Person("无为治", 15, "荷兰", 'A'));

        /*计数： count
        平均值： averagingInt、 averagingLong、 averagingDouble
        最值： maxBy、 minBy
        求和： summingInt、 summingLong、 summingDouble*/
        Long collect = people.stream().collect(Collectors.counting());
        System.out.println("计数" + collect);
        Double collect1 = people.stream().collect(Collectors.averagingInt(item -> item.getAge()));
        System.out.println("年龄平均值" + collect1);
        Optional<Person> collect2 = people.stream().collect(Collectors.maxBy(((o1, o2) -> o1.getAge() - o2.getAge())));
        System.out.println("年龄最大值 = " + collect2);
        Optional<Person> collect3 = people.stream().collect(Collectors.minBy(((o1, o2) -> o1.getAge() - o2.getAge())));
        System.out.println("年龄最小值 = " + collect3);
        //搜集为一个新的集合
        //获取过滤后的筛选后的指定数据
        Set<String> set = people.stream().filter(item -> item.getAge() > 20)
                .filter(item -> item.getCountry().equals("中国"))
                .map(item -> item.getName())
                .collect(Collectors.toSet());
        System.out.println("新的集合 = " + set);

        //分组操作
        //根据性别分组
        Map<Character, List<Person>> collect4 = people.stream().collect(Collectors.groupingBy(item -> item.getSex()));
        System.out.println(collect4);
        System.out.println();

    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
class Person{
    private String name;
    private Integer age;
    private String country;
    private char sex;
}